package com.rf.richfitwheel.workflow.listener;


import com.rf.richfitwheel.admin.utils.UserUtil;
import com.rf.richfitwheel.workflow.conf.WorkflowContants;
import com.rf.richfitwheel.workflow.entity.WorkflowMsgVo;
import com.rf.richfitwheel.workflow.model.WfProcessTask;
import com.rf.richfitwheel.workflow.rabbitmq.WorkflowSender;
import com.rf.richfitwheel.workflow.service.WfProcessService;
import com.rf.richfitwheel.workflow.service.WfProcessTaskService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.IdentityLink;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 动态用户任务分配
 *
 * @author ZML
 */
@Component("processTaskListener")
public class ProcessTaskListener implements TaskListener {
    /**
     *
     */
    private static final long serialVersionUID = 2190559253653576032L;

    protected static final Logger log = LoggerFactory.getLogger(ProcessTaskListener.class);

    @Autowired
    protected RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private WfProcessTaskService wfProcessTaskService;
    @Autowired
    private WfProcessService wfProcessService;
    @Autowired
    private WorkflowSender workflowSender;

    @Override
    public void notify(DelegateTask delegateTask) {
        WorkflowMsgVo workflowMsgVo = new WorkflowMsgVo();//消息队列信息
        workflowMsgVo.setUserVO(UserUtil.getUser());
        Map<String, Object> variables = delegateTask.getVariables();
        ProcessDefinition processDefinition = this.repositoryService.getProcessDefinition(delegateTask.getProcessDefinitionId());
        String taskDefinitionKey = delegateTask.getTaskDefinitionKey();        //directorAudit
        String moduleType = (String) variables.get("moduleType");//模块类型
        String queueName = (String) variables.get("queueName");//队列名称
        if (com.rf.richfitwheel.common.utils.StringUtils.isBlank(queueName)) {
            log.warn("ID为{}的流程消息队列名称是空的", delegateTask.getProcessInstanceId());
        }
        String startUserId = (String) variables.get("startUserId");//发起人
        String taskState = delegateTask.getTaskState();
        workflowMsgVo.setModuleType(moduleType);
        workflowMsgVo.setQueueName(queueName);//队列名称
        workflowMsgVo.setEventName(WorkflowContants.EVENTNAME_TASK_CREATE);//
        workflowMsgVo.setProcessDefinitionId(processDefinition.getId());
        workflowMsgVo.setProcessDefinitionKey(processDefinition.getKey());
        workflowMsgVo.setProcessDefinitionName(processDefinition.getName());
        workflowMsgVo.setProcessInstanceId(delegateTask.getProcessInstanceId());
        workflowMsgVo.setStartUserId(startUserId);
        workflowMsgVo.setTaskId(delegateTask.getId());
        workflowMsgVo.setTaskName(delegateTask.getName());
        workflowMsgVo.setTaskState(taskState);
        workflowMsgVo.setVariables(variables);

        //log.info("任务审批人:" + delegateTask.getCandidates());
        boolean isSend = true;
        String approveUserId = "";
        ActivityImpl firstUserTask = wfProcessService.getFirstUserTask(processDefinition);
        if (taskDefinitionKey.equals(firstUserTask.getId())) {
            if (taskState.equals(WorkflowContants.ProcessResult.CREATE.getValue())) {
                isSend = false;
            }
            approveUserId = (String) variables.get("startUserId");
        } else {
            if (variables.containsKey("approveUserId")) {
                approveUserId = (String) variables.get("approveUserId");
                runtimeService.removeVariable(delegateTask.getProcessInstanceId(), "approveUserId");//当前任务设置审批人后删除
                variables.remove("approveUserId");
            }
        }
        if (StringUtils.isNotBlank(approveUserId)) {//是否指定审批人
            delegateTask.setAssignee(approveUserId);
            workflowMsgVo.setApproveType("1");//assignee
            workflowMsgVo.setApproveIds(approveUserId);//当前任务审批人
        } else {
            if (StringUtils.isNotBlank(delegateTask.getAssignee())) {//任务已经有审批人
                workflowMsgVo.setApproveType("1");//assignee
                workflowMsgVo.setApproveIds(delegateTask.getAssignee());//当前任务审批人
            } else if (delegateTask.getCandidates().size() > 0) {//任务有修行组
                Set<IdentityLink> identityLinks = delegateTask.getCandidates();
                workflowMsgVo.setApproveType("3");//assignee
                workflowMsgVo.setApproveIds(identityLinks.iterator().next().getGroupId());//当前任务审批人
            } else {//什么都没有情况读取流程任务配置设置审批人/候选人/候选组
                //获取当审批设置设置审批人或者候选人或者候选组
                WfProcessTask wfProcessTask = this.wfProcessTaskService.findByProDefIdAndTaskDefKey(processDefinition.getId(), taskDefinitionKey);
                String assigneeType = wfProcessTask.getAssigneeType();
                String ids = wfProcessTask.getCandidateIds();
                workflowMsgVo.setApproveType(assigneeType);
                workflowMsgVo.setApproveIds(ids);
                switch (assigneeType) {
                    case "1": {//assignee
                        delegateTask.setAssignee(ids);
                        log.info("assignee id: " + ids);
                        break;
                    }
                    case "2": {//candidateUser
                        String[] userIds = ids.split(",");
                        List<String> users = new ArrayList<>();
                        for (int i = 0; i < userIds.length; i++) {
                            users.add(userIds[i]);
                        }
                        delegateTask.addCandidateUsers(users);
                        log.info("候选人审批 ids: " + ids);
                        break;
                    }
                    case "3": {//candidateGroup
                        String[] groupIds = ids.split(",");
                        List<String> groups = new ArrayList<>();
                        for (int i = 0; i < groupIds.length; i++) {
                            groups.add(groupIds[i]);
                        }
                        delegateTask.addCandidateGroups(groups);
                        log.info("候选组审批 ids: " + ids);
                        break;
                    }
                }
            }
        }

        if (isSend) {
            workflowSender.sendWorkflowMsg(workflowMsgVo);//向消息队列发送消息
        }
    }
}
